<?php
/**
 * Created by PhpStorm.
 * User: YAN
 * Date: 2017/7/17
 * Time: 14:05
 */

namespace App\Http\Controllers\API;


use App\Models\AdminLog;
use App\Models\Semester;
use App\Http\Requests\SemesterRequest as Request;
use Illuminate\Support\Facades\Auth;

class SemesterController
{
    public function getList()
    {
        $Semesters = Semester::query()->get();
        $result = [];
        if ($Semesters) {
            foreach ($Semesters as $items) {
                $item['name'] = $items->s_name;
                $item['id'] = $items->id;
                $result[] = $item;
            }
            return ['success' => 'true', 'data' => $result, 'message' => '学期列表'];
        } else {
            return response(['success' => 'false', 'message' => '无学期信息'], 406);
        }
    }

    public function getSemesterList()
    {
        $Semesters = Semester::query()->get();
        $result = [];
        if ($Semesters) {
            foreach ($Semesters as $items) {
                $result[$items->id] = $items->s_name;
            }
        }
        return $result;
    }

    public function index(Request $request)
    {
        $queryString = $request->get('query', '');
        $models = Semester::query()
            ->where('s_name', 'like', '%' . $queryString . '%')
            ->paginate();
        return $models;
    }


    /**
     * 添加科室
     * @param Request $request
     * @return mixed
     */
    public function store(Request $request)
    {
        $model = new Semester();
        $model->fill($request->all());
        $model->times_temp = strtotime($model->begin);
        $days = $this->format($model->begin, $model->end);
        $model->s_week = count($days);
        $logs = new AdminLog();
        $logs->admin = Auth::user()->id;
        $logs->logs = '新增学期信息：'. $model->s_name;
        if (!$logs->save()) {
            throw new \Exception('记录保存失败');
        }
        if ($model->save()) {
            return $model;
        } else {
            return response($model->getErrors()->toArray(), 406);
        }
    }

    public function format($b, $e)
    {
        $startDate = $b;
//结束时间
        $endDate = $e;
//跨越天数
        $n = (strtotime($endDate) - strtotime($startDate)) / 86400;
//结束时间加一天(sql语句里用的是小于和大于，如果有等于的话这句可以不要)
        $endDate = date("Y-m-d 00:00:00", strtotime("$endDate +1 day"));
//判断，跨度小于7天，可能是同一周，也可能是两周
        if ($n < 7) {
//查开始时间 在 那周 的 位置
            $day = date("w", strtotime($startDate)) - 1;
//查开始时间 那周 的 周一
            $week_start = date("Y-m-d 00:00:00", strtotime("$startDate -{$day} day"));
//查开始时间 那周 的 周末
            $day = 7 - $day;
            $week_end = date("Y-m-d 00:00:00", strtotime("$startDate +{$day} day"));
//判断周末时间是否大于时间段的结束时间，如果大于，那就是时间段在同一周，否则时间段跨两周
            if ($week_end >= $endDate) {
                $weekList[] = array($startDate, $endDate);
            } else {
                $weekList[] = array($startDate, $week_end);
                $weekList[] = array($week_end, $endDate);
            }
        } else {
//如果跨度大于等于7天，可能是刚好1周或跨2周或跨N周，先找出开始时间 在 那周 的 位置和那周的周末时间
            $day = date("w", strtotime($startDate)) - 1;
            $week_start = date("Y-m-d 00:00:00", strtotime("$startDate -{$day} day"));
            $day = 7 - $day;
            $week_end = date("Y-m-d 00:00:00", strtotime("$startDate +{$day} day"));
//先把开始时间那周写入数组
            $weekList[] = array($startDate, $week_end);
//判断周末是否大于等于结束时间，不管大于(2周)还是等于(1周)，结束时间都是时间段的结束时间。
            if ($week_end >= $endDate) {
                $weekList[] = array($week_end, $endDate);
            } else {
//N周的情况用while循环一下，然后写入数组
                while ($week_end <= $endDate) {
                    $start = $week_end;
                    $week_end = date("Y-m-d 00:00:00", strtotime("$week_end +7 day"));
                    if ($week_end <= $endDate) {
                        $weekList[] = array($start, $week_end);
                    } else {
                        $weekList[] = array($start, $endDate);
                    }
                }
            }
        }
        return $weekList;
    }


    /**
     * 修改员工
     * @param User $User
     * @param Request $request
     * @return mixed
     */
    public function update(Semester $Semester, Request $request)
    {
        $Semester->fill($request->all());
        $Semester->times_temp = strtotime($Semester->begin);
        $days = $this->format($Semester->begin, $Semester->end);
        $Semester->s_week = count($days);
        $logs = new AdminLog();
        $logs->admin = Auth::user()->id;
        $logs->logs = '修改学期信息：'.  $Semester->s_name;
        if (!$logs->save()) {
            throw new \Exception('记录保存失败');
        }
        if ($Semester->save()) {
            return $Semester;
        } else {
            return response($Semester->getErrors()->toArray(), 406);
        }
    }


    /**
     * 删除
     * @param $id
     * @return mixed
     */
    public function destroy($id)
    {
        $model = $this->findModel($id);
        try {
            $logs = new AdminLog();
            $logs->admin = Auth::user()->id;
            $logs->logs = '删除学期信息：'. $model->s_name;
            if (!$logs->save()) {
                throw new \Exception('记录保存失败');
            }
            $model->delete();
            return ['state' => 'success'];
        } catch (\Exception $e) {
            return ['state' => 'failed', 'message' => $e->getMessage()];
        }
    }


    /**
     * 返回单个实例
     * @param User $user
     * @return mixed
     */
    public function show(Semester $Semester)
    {
        return $Semester;
    }


    /**
     * @param $id
     * @return Staff
     */
    public function findModel($id)
    {
        $model = Semester::findOrFail($id);
        return $model;
    }
}